<?php
/*                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                            O\ = /O
 *                        ____/`---'\____
 *                      .   ' \\| |// `.
 *                       / \\||| : |||// \
 *                     / _||||| -:- |||||- \
 *                       | | \\\ - /// | |
 *                     | \_| ''\---/'' | |
 *                      \ .-\__ `-` ___/-. /
 *                   ___`. .' /--.--\ `. . __
 *                ."" '< `.___\_<|>_/___.' >'"".
 *               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *                 \ \ `-. \_ __\ /__ _/ .-` / /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *
 *         .............................................
 *                  佛祖保佑             永无BUG
 *
 * ======================================================
 * @author: Ethan Lu <ethan.lu@qq.com>
 * 
 */

namespace frontend\components\sms;

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\InputWidget;

class SmsWidget extends InputWidget
{
    public $buttonOptions = [
        'class' => 'btn btn-theme btn-block',
        'id' => 'get_code',
    ];

    /** @var string 手机号码字段 */
    public $mobile = 'mobile';

    /** @var string 验证码字段 */
    public $code = 'code';

    public $template = "<div class='clearfix'>
                            <div class=\"col-md-7\">
                                {input}
                            </div>
                            <div class=\"col-md-5\">
                                {button}
                            </div>
                        </div>";

    public $options = [
        'placeholder' => '手机验证码',
        'class' => 'form-control',
        'tabindex' => '2',
    ];

    public $mobileId = 'mobile';

    public $route = '/api/sms';

    /**
     * Executes the widget.
     * @return string the result of widget execution to be outputted.
     */
    public function run()
    {
        $this->registerClientScript();
        if($this->hasModel()) {
            $input = Html::activeTextInput($this->model, $this->attribute, $this->options);
        } else {
            $input = Html::textInput($this->name, $this->value, $this->options);
        }

        $button = Html::button('免费获取验证码', $this->buttonOptions);
        echo strtr($this->template, [
            '{input}' => $input,
            '{button}' => $button,
        ]);
    }

    public function registerClientScript()
    {
        $view = $this->getView();
        $route = Url::to($this->route);
        $idField = $this->buttonOptions['id'];
        $view->registerJs("\$('#$idField').click(function(){
            var mobile = \$('#$this->mobile').val();
            if(mobile == '') {
                \$('.field-$this->mobile').addClass('has-error').find('.help-block').html('手机号码不能为空');
            }
            if(!(/^1[3|4|5|8][0-9]\d{8}$/.test(mobile))) {
                \$('.field-$this->mobile').addClass('has-error').find('.help-block').html('手机号码不正确');
                return false;
            }

            \$.post('', { $this->mobile: mobile}, function(data) {

                if(data.$this->mobile) {
                    \$('.field-$this->mobile').addClass('has-error').find('.help-block').html(data.$this->mobile[0]);
                    return;
                }

                \$.get('$route', {mobile: mobile, _csrf:'".\Yii::$app->getRequest()->getCsrfToken()."'}, function(data){
                    var data = JSON.parse(data);
                    if(data.status) {
                        set_time($('#$idField'));
                    } else {
                        if(!data.return) {
                            alert(data.msg);
                            return false;
                        }
                        countdown= 60 - data.return;
                        set_time($('#$idField'));
                    }
                });
            });

        });

        var countdown=60;
        function set_time(obj) {
            if (countdown == 0) {
                obj.attr('disabled', false);
                obj.text('免费获取验证码');
                countdown = 60;
                return;
            } else {
                obj.attr('disabled', true);
                obj.text(countdown + '秒后重新获取');
                countdown--;
            }

            setTimeout(function() {
                set_time(obj);
            }, 1000)
        }

        ");
    }


}